/**
 * Created by feifan.gou@gamil.com on 2025/4/25 16:31.
 */
import axios from 'axios';
import {ElNotification} from 'element-plus'
import router from "../router.js";

const api = axios.create({
    baseURL: import.meta.env.VITE_API_HOST, // 基础 URL
});

export function post(url, data, successHook, failHook) {

    return request(url, 'post', data, successHook, failHook);
}

export function get(url, successHook, failHook) {

    return request(url, 'get', {}, successHook, failHook);
}

async function request(url, method = 'get', data, successHook, failHook) {

    let response;
    try {
        if (method === 'get') {
            response = await api.get(url, {
                timeout: 120000,
                headers: {
                    'Authorization': localStorage.getItem('token')
                }
            });
        } else if (method === 'post') {
            response = await api.post(url, data, {
                timeout: 120000,
                headers: {
                    'Authorization': localStorage.getItem('token')
                }
            });
        }
        if (response) {
            if (response && response.status === 200) {
                let responseData = response.data;
                if (responseData.status === '0000') {
                    if (successHook && typeof successHook === 'function') {
                        successHook(responseData.data);
                    }
                } else if (responseData.status === '401') {
                    ElNotification({
                        title: 'Error',
                        message: responseData.message,
                        duration: 1500,
                        type: 'error',
                        onClose: () => {
                            router.push('/login');
                        }
                    })
                } else {
                    if (failHook && typeof failHook === 'function') {
                        failHook(responseData.message);
                    } else {
                        ElNotification({
                            title: 'Error',
                            message: responseData.message,
                            duration: 1500,
                            type: 'error'
                        })
                    }
                }
            }
        } else {
            ElNotification({
                title: 'Error',
                message: '网络错误',
                type: 'error',
            })
        }
    } catch (error) {
        ElNotification({
            title: 'Error',
            message: '网络错误',
            type: 'error',
        })
    }
}